(function() {
	var $ = require(L('$'));
	var textFields = [], currentTextField,scrollView, scrollViewHeight;

	var navButtons = Ti.UI.createButtonBar({
		labels : ['Previous', 'Next'],
		top : 100,
		style : Ti.UI.iPhone.SystemButtonStyle.BAR,
		height : 30,
		width : 'auto'
	});	
	
	navButtons.addEventListener('click', function(e){
		var currentIndex = textFields.indexOf(currentTextField);
		var nextIndex = Math.min(currentIndex + 1, textFields.length - 1);
		var prevIndex = Math.max(currentIndex - 1, 0);
		var nextItem = currentIndex < textFields.length - 1 ? textFields[currentIndex + 1] : textFields[textFields.length - 1];
		var prevItem = currentIndex > 0 ? textFields[currentIndex - 1] : textFields[0];
		if (e.index == 1) {
			nextItem.focus();
		} else {
			prevItem.focus();
		}
	});

	var done = Ti.UI.createButton({
		title : 'Done',
		style : Ti.UI.iPhone.SystemButtonStyle.DONE,
		height : 30
	});
	$.click(done, function(){
		toolbar.hide();
		//$.blur(textFields);
		currentTextField.blur();
		$.repeat(function() {
			scrollView.scrollTo(0,0);
		}, 5);
	});
	var flexSpace = Ti.UI.createButton({
		systemButton : Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE
	});

	 var toolbar = Ti.UI.iOS.createToolbar({
	 	items:[navButtons, flexSpace, done],
	    borderTop:true,
	    borderBottom:false,
	    translucent:true
	});
	
	var text_field = {};
	text_field.create = function(hint, autoCapital, isPassword){
		var textfield = Ti.UI.createTextField({
			hintText : hint,
			keyboardToolbar : toolbar,
			clearButtonMode : Ti.UI.INPUT_BUTTONMODE_ONFOCUS,//Ti.UI.INPUT_BUTTONMODE_ALWAYS,
			autocorrect : false,
			autocapitalization : autoCapital || Ti.UI.TEXT_AUTOCAPITALIZATION_NONE,
			passwordMask : isPassword || false,
			//Ti.UI.TEXT_AUTOCAPITALIZATION_WORDS, //Ti.UI.TEXT_AUTOCAPITALIZATION_SENTENCES, //Ti.UI.TEXT_AUTOCAPITALIZATION_ALL
			backgroundImage : L('bg_textbox'),
			color : L('color_gray'),
			height : '40dip',
			width : '280dip',
			top : '7dip',
			focusable : 'true',
			font : {
				fontSize : '14dip',
				fontFamily : L('font_default')
			},
			borderWidth : 0,
			paddingLeft : 7
		});
		$.on('focus', textfield, function(){
			toolbar.show();
			currentTextField = textfield;
			if(scrollView)
				scrollView.height= $.isIphone5() ? 240 : 153;
		});
		$.on('blur', textfield, function(){
			if(scrollView){
				scrollView.height = scrollViewHeight;
			}
		});
		textfield.val = function(value){
			if($.isNull(value) && value != '')
				return textfield.value;
			textfield.value = value;
		};
		return textfield;
	};
	
	text_field.init = function(_textFields, _scrollView, _scrollViewHeight){
		textFields = _textFields;
		scrollView = _scrollView;
		scrollViewHeight = _scrollViewHeight;
	}

	module.exports = text_field;
})();

